package com.huawei.struts.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;

import com.huawei.struts.form.LoginForm;
import com.huawei.struts.service.UserTService;
import com.huawei.struts.util.CommonUtil;
import com.huawei.struts.util.PageBean;
import com.st.model.UserT;

public class LoginAction extends BaseAction {
	
	private static Logger logger=Logger.getLogger(LoginAction.class);
	private final String returnUrl="/login.do?method=toList";
	private final String toImport="/login.do?method=toImport";
	
	
	//UserService userService=new UserImp();
	private UserTService userTService;

	public void setUserTService(UserTService userTService) {
		this.userTService = userTService;
	}

	@SuppressWarnings("deprecation")
	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm userForm =(LoginForm)form;
		
		logger.info("into login method");
		
		boolean flag=userTService.login(userForm.getUser());
		if(flag)
		{
			request.getSession().setAttribute("user", userTService.getUserByName(userForm.getUser().getSname()));
			request.getSession().setMaxInactiveInterval(-1);//登陆后永不超时
			Object path=(Object)request.getSession().getAttribute("path");
			logger.info("login successful");
			
			if(path==null)
			{
				return mapping.findForward("home");
				
			}
			else
			{
				return new ActionForward(path.toString().replaceAll(request.getContextPath(), "/"));
			}
			
		}
		else
		{
				return mapping.getInputForward();
		}
		 
		
	}

	
	public ActionForward toUpdate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm userForm =(LoginForm)form;
		this.saveToken(request);
		Integer sid=Integer.parseInt(request.getParameter("sid"));
		userForm.setUser(userTService.getUserById(sid));
		return mapping.findForward("toUpdate");
		 
		
	}
	public ActionForward toList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm userForm =(LoginForm)form;
		userForm.setUser(new UserT()); 
		return mapping.findForward("toList");
	}
	
	public ActionForward getContext(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm userForm =(LoginForm)form;
		userForm.getUser().setSname(CommonUtil.isoToGB(userForm.getUser().getSname()));//转码
		PageBean pageBean=userTService.queryForPage(userForm.getUser(),userForm.getPageBean());
		//Thread.sleep(2000);
		JSONArray jsonArray = JSONArray.fromObject(pageBean.getList());
		this.responseResult(request, response, jsonArray.toString());
		return null;
	}
	
	public ActionForward getPageCount(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm userForm =(LoginForm)form;
		int allRow=userTService.getTotalCount(userForm.getUser());
		int pageSize=userForm.getPageBean().getPageSize();
		int pageCount=PageBean.countTotalPage(pageSize, allRow);
		this.responseResult(request, response, allRow+":"+pageCount); 
		return null;	
	}
	public ActionForward toAdd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm userForm =(LoginForm)form;
		//this.saveToken(request);
		return mapping.findForward("toAdd");
	}
	
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm userForm =(LoginForm)form;
		userTService.addUser(userForm.getUser());
		
		return super.goSuccess("操作成功", returnUrl, request, response, mapping);
		/*if(this.isTokenValid(request,true))
		{
			userTService.addUser(userForm.getUser());
			
			return super.goSuccess("操作成功", returnUrl, request, response, mapping);
		}
		else
		{
			return super.goFail("表单不能重复提交", returnUrl, request, response,mapping);
		}*/
	}
	
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm userForm =(LoginForm)form;
		
		if(this.isTokenValid(request,true))
		{
			userTService.modify(userForm.getUser());
			return super.goSuccess("操作成功", returnUrl, request, response, mapping);
		}
		else
		{
			return super.goFail("表单不能重复提交", returnUrl, request, response,mapping);
		} 
		
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm userForm =(LoginForm)form; 
		//Thread.sleep(2000);
		Integer sid=Integer.parseInt(request.getParameter("sid"));
		userForm.getUser().setSid(sid);
		boolean flag=userTService.delete(userForm.getUser()); 
		if(flag)
		{
			this.responseResult(request, response, "0");
		}
		return null;
	}
	public void loginVlidate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm userForm =(LoginForm)form; 
		String vcode=request.getParameter("vcode");
		String sname=request.getParameter("sname");
		String spassword=request.getParameter("spassword");
		String randImg=(String)request.getSession().getAttribute("randImg");
	    if(vcode.toLowerCase().equals(randImg.toLowerCase()))
	    {
	    	userForm.getUser().setSname(sname);
			userForm.getUser().setSpassword(spassword);
			boolean flag=userTService.login(userForm.getUser());
			if(flag==false)
			{
				this.responseResult(request, response, "0");
			}
	    }
	    else
	    {
	    	this.responseResult(request, response, "1");
	    }
		
		 
	}
	public void responseResult(HttpServletRequest request, HttpServletResponse response,String result) throws IOException
	{
		response.setContentType("text/html;charset=utf-8");           
		PrintWriter out=response.getWriter();   
		request.setCharacterEncoding("utf-8");
	    out.print(result);
	    out.close();
	}
	public ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm userForm =(LoginForm)form;
		request.getSession().setAttribute("user", null);
		request.getSession().setAttribute("path", null);
		return mapping.getInputForward();
	}
	
	public ActionForward export(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm userForm =(LoginForm)form;
		String basePath=request.getSession(true).getServletContext().getRealPath("/ExcelFile/upload");
		String fileName=basePath+"/"+UUID.randomUUID()+".xls";
		 File file=new File(fileName);
		List list=userTService.export(userForm.getUser());
		try {       
            WritableWorkbook book = Workbook.createWorkbook(file);         
            WritableSheet sheet = book.createSheet("Sheet_1", 0);  
            WritableFont wf = new WritableFont(WritableFont.ARIAL, 15,
           	     WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
           	     jxl.format.Colour.CORAL); // 定义格式 字体 下划线 斜体 粗体 颜色
           	   WritableCellFormat wcf = new WritableCellFormat(wf); // 单元格定义
           	   
           	   wcf.setBackground(jxl.format.Colour.BLUE); // 设置单元格的背景颜色
           	   wcf.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式
           	   String[] title={"id","name","password"};
           	   for(int i=0;i<title.length;i++)
           	   {
           		   sheet.setColumnView(i, 30); // 设置列的宽度
           		   sheet.addCell(new Label(i, 0, title[i],wcf));
           		    
           	   }
       		   for(int j=0;j<list.size();j++)
       		   {
       			   UserT user=(UserT) list.get(j);
       			   sheet.addCell(new Label(0, j+1, user.getSid().toString())); 
       			   sheet.addCell(new Label(1, j+1, user.getSname().toString()));  
       			   sheet.addCell(new Label(2, j+1, user.getSpassword().toString()));
            	  
       		   }
	            book.write();       
	            book.close();    
        } catch (Exception e) {    
            e.printStackTrace();    
        }
        super.downloadFile(file.getPath(), file.getName(), request, response);
		 
		if(file.exists())
		{
			file.delete();
		}
		return null;
	}
	
	
	
	public ActionForward toImport(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception{
		return mapping.findForward("toImport");	
	}
	
	public ActionForward downlaodTemplate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception{
		String basePath=request.getSession(true).getServletContext().getRealPath("/ExcelFile/template");
		String templateName="user_import_template.xls";
		String path=basePath+"/"+templateName;
		super.downloadFile(path, templateName, request, response);
		return null;	
	}
	public ActionForward importExcelData(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm userForm =(LoginForm)form;
		FormFile file1=userForm.getFile();
		String dir=request.getSession(true).getServletContext().getRealPath("/ExcelFile/upload");
		SimpleDateFormat dateformat1=new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String date=dateformat1.format(new Date());
		String fileName=request.getSession().getId()+"_"+date+"_"+file1.getFileName();
		OutputStream fos=null;
		if(file1.getFileSize()>0)
		{
            fos=new FileOutputStream(dir+"/"+fileName);   
            fos.write(file1.getFileData(),0,file1.getFileSize());   
            fos.flush();   
            fos.close();  
            boolean flag= userTService.importExcelData(dir+"/"+fileName);
           	if(flag)
           	{
    			return super.goSuccess("导入成功", toImport, request, response,mapping);
           	}
           	else
           	{
    			return super.goFail("导入失败", toImport, request, response,mapping);
           	}
		}
		else
		{
			return super.goFail("文件不能为空", toImport, request, response,mapping);
		}
		
	}
	

}
